<template>
  <div>
    <div
      style="background: #fff; padding: 20px;min-height: 89vh;margin-top: 80px;width: 80%;border-radius: 8px;margin-left: 10%;"
    >
      <h4>个人基础信息</h4>
      <div style="display: flex;">
        <el-form
          style="margin: 20px auto;"
          :model="form"
          status-icon
          :rules="rules"
          ref="form"
          label-width="100px"
          class="demo-form"
        >
          <el-form-item label="账号" prop="account">
            <el-input
              type="text"
              disabled=""
              v-model="form.account"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="form.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="头像" prop="avator">
            <div style="display: flex;align-items: center;">
            <img :src="form.avator" style="width: 80px;height: 80px;margin-right: 10px;" />
            <el-upload
              class="avatar-uploader"
              :action="'/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <el-button size="mini" type="primary">修改头像</el-button>
            </el-upload>
            </div>

          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="text"
              v-model="form.password"
              auto-complete="off"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
          <el-form-item label="喜好" prop="likes">
            <el-checkbox-group v-model="form.likes">
              <el-checkbox label="运动保健型"></el-checkbox>
              <el-checkbox label="游乐刺激型"></el-checkbox>
              <el-checkbox label="观赏体验型"></el-checkbox>
              <el-checkbox label="文化休闲型"></el-checkbox>
              <el-checkbox label="室内消遣型"></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <div style="display: flex;">
        <el-button
          size="mini"
          style="margin: auto;"
          v-if="userInfo.username"
          @click="update"
          type="primary"
          >修改</el-button
        >
      </div>

      <div
        v-if="userInfo.stars.length"
        style="line-height: 40px;font-size: 14px;color: #ff9d00;font-weight: bold;"
      >
        我的收藏
      </div>
      <div class="my-star" v-if="userInfo.stars">
        <div
          class="each"
          v-for="(item, index) in userInfo.stars"
          :key="index"
          @click="toDetail(item.funInfo)"
        >
          <div style="width: 200px;height: 100px;overflow: hidden;">
            <img v-if="item.funInfo" :src="item.funInfo.pics.split(',')[0]" alt="" />
          </div>

          <div v-if="item.funInfo" class="funName">{{ item.funInfo.funName }}</div>
        </div>
      </div>

      <div
        v-if="userInfo.tickets.length"
        style="line-height: 40px;font-size: 14px;color: #ff9d00;font-weight: bold;"
      >
        我已购买
      </div>
      <div class="my-star" v-if="userInfo.tickets">
        <div
          class="each-ticket"
          v-for="(item, index) in userInfo.tickets"
          :key="index"
        >
          <img @click="toDetail(item)" :src="item.pic" alt="" />
          <div @click="toDetail(item)"><span>景点名称</span>{{item.funName}}</div>
          <div><span>门票日期</span>{{item.data}}</div>
          <div><span>票价</span>{{item.price}}</div>
          <div><span>张数</span>{{item.count}}</div>
          <div><span>购买日期</span>{{item.buyTime}}</div>


          <el-button size="mini" type="danger" class="cancel" @click="cancelFun(item)">取消订单</el-button>
        </div>
      </div>

      <div
        v-if="userInfo.comments && userInfo.comments.length"
        style="line-height: 40px;font-size: 14px;color: #ff9d00;font-weight: bold;"
      >
        我的评论
      </div>
      <div class="my-star" v-if="userInfo.comments">
        <div
          class="each-ticket"
          v-for="(item, index) in userInfo.comments"
          @click="toDetail(item.funInfo, 'comment')"
          :key="index"
        >
          <div><span>景点名称</span>{{item.funInfo.funName}}</div>
          <div><span>评论</span>{{item.comment.content}}</div>
          <div><span>评论日期</span>{{item.comment.createTime}}</div>
        </div>
      </div>
      
      <div style="height: 1px;width: 100%;margin-top: 50px;"></div>
    </div>
    
    <el-dialog
      title="取消订单"
      :visible.sync="cancelVisible"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <el-input-number v-model="cnt" :min="1" :max="max"></el-input-number>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitCancel">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { updateUser, getUserInfo, getFunById,updateFun, deleteTicket } from "../service";
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
        avator: '',
        likes: [],
      },
      cnt: 0,
      max: 0,
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        likes: [{ required: true, message: "请选择你的喜好", trigger: "blur" }],
      },
      userInfo: {},
      cancelVisible: false
    };
  },
  created() {
    let ls = localStorage.getItem("meiyaWebInfo");
    if (ls) {
      this.userInfo = JSON.parse(ls);
    }
    if (this.userInfo._id) {
      this.getUser()
    }
  },
  methods: {
    getUser() {
      getUserInfo(this.userInfo._id).then((res) => {
        this.userInfo = {
          ...res.data,
          likes: res.data.likes.split(','),
          stars: res.like,
          tickets: res.tickets,
          comments: res.comments
        };
        if (this.userInfo.comments.length) {
          this.userInfo.comments.forEach((v, i) => {
            this.userInfo.comments[i].comment.createTime = moment(v.comment.createTime).format('YYYY-MM-DD HH:mm:ss')
          })
        }
        this.form = {
          ...this.userInfo,
        }; 
        console.log(this.userInfo)
      });
    },
    handleClose() {
      this.cancelVisible = false;
    },
    commitCancel() {
      let funId = this.userInfo.tickets[this.index].funId
      if (this.cnt === this.max) {
        this.userInfo.tickets.splice(this.index, 1)
      } else {
        this.userInfo.tickets[this.index].count = this.max - this.cnt
      }
      // 查询玩乐点详情
      getFunById(funId).then((fun) => {
        fun = fun.data
        fun.tickets = JSON.parse(fun.tickets)
        let index = fun.tickets.findIndex(v => v.userId === this.userInfo._id)
        if (this.cnt === this.max) {
          fun.tickets.splice(index, 1)
        } else {
          fun.tickets[index].count = this.max - this.cnt
        }
        // 更新玩乐点
        updateFun(funId, {
          tickets: JSON.stringify(fun.tickets)
        }).then(res => {
          // 调保存接口
          updateUser(this.userInfo._id, {
            tickets: JSON.stringify(this.userInfo.tickets)
          }).then(res => [
            this.cancelVisible = false
          ])
        })
      })
      
    },
    handleAvatarSuccess(result) {
      this.form.avator = result.url;
    },
    toDetail(params, comment = false) {
      this.$router.push({
        name: "Detail",
        params: {
          id: params.funId || params._id,
        },
      });
      localStorage.setItem(
        "meiyaFunDetail",
        JSON.stringify({
          id: params._id,
        })
      );
    },
    update() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateUser(this.userInfo._id, {
            password: this.form.password,
            username: this.form.username,
            likes: this.form.likes.join(','),
            avator: this.form.avator
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('修改成功')
              location.reload()
              localStorage.setItem('meiyaWebInfo', JSON.stringify(this.userInfo))
            }
          })
        }
      })
    },
    cancelFun(item) {
      this.$confirm('您将取消订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTicket(item._id).then(res => {
          if (res.code === 200) {
            this.$message.success('取消成功')
            this.getUser()
          }
        })
      })
    }
  },
};
</script>

<style lang="scss" scoped>
h4 {
  text-align: center;
  font-weight: bold;
}
.my-star {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  & > div {
    cursor: pointer;
  }
  img {
    width: 200px;
    height: 100px;
    transition: all 0.3s;
  }
  .funName {
    width: 200px;
    text-align: center;
    line-height: 30px;
  }

  .each {
    overflow: hidden;
  }

  .each-ticket {
    display: flex;
    align-items: center;
    border: 1px dashed gray;
    padding: 12px;
    width: 100%;
    color: #666;
    position: relative;

    &>div {
      margin-left: 10px;
    }

    img {
      width: 100px;
    }

    span {
      color: #ff9d00;
      font-weight: bold;
      margin-right: 3px;
    }

    .cancel {
      position: absolute;
      right: 20px;
      top: 20px;
    }
  }

  .each:hover {
    img {
      transform: scale(1.1);
    }
    .funName {
      color: #ff9d00;
    }
  }
}
::v-deep .el-upload__input {
  display: none;
}
</style>
